package actions;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import objects.info.ClusterStatusInfo;
import objects.info.JobStatusInfo;

import utils.Utils;


public class JobTimer {
	public String name;
	int nodes, procs,walltime;
	Calendar cal;
	Date startTime;
	Date endQueueTime;
	Date startRunTime;
	Date endRunTime;
	int queuetime;
	double runtime;
	SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
	JobStatusInfo jsi;
	
	public JobTimer(String n, int nodes, int procs,int wt) {
		this.name = n;
		this.nodes = nodes;
		this.procs = procs;
		this.walltime = wt;
	}

	public void start() {
		cal = Calendar.getInstance();
		startTime = cal.getTime();
		jsi = new JobStatusInfo(nodes,procs,walltime);
	}

	public void endQueued() throws Exception {
		cal = Calendar.getInstance();
		endQueueTime = cal.getTime();
		//Utils.out(endQueueTime.getTime() +" "+ startTime.getTime()+ " "+(endQueueTime.getTime() - startTime.getTime()));
		queuetime = (int) ((endQueueTime.getTime() - startTime.getTime()) / 1000);
		jsi.setQueuetime(queuetime);
		startRunTime = endQueueTime;
		if(jsi.freenodes == 0 && jsi.freeprocs == 0 && jsi.activejobs == 0)
			return;
		Utils.out("+ job "+name+" was queued for "+queuetime);
		Utils.out("+ sending information");
		Utils.ws.send(jsi);
		Utils.out("+ sending done");
		
	}

	public void endJob() {
		cal = Calendar.getInstance();
		endRunTime = cal.getTime();
		runtime = (double) (endRunTime.getTime() - startRunTime.getTime()) / 1000;
	}

	public String toString() {
		return ("Start Time :\t" + sdf.format(startTime) + "\n"
				+ "End Queue Time:\t" + sdf.format(endQueueTime) + "\n"
				+ "End Run Time:\t" + sdf.format(endRunTime) + "\n"
				+ "Time in queue:\t" + queuetime + "s\n" + "Time running:\t"
				+ runtime + "s\n");
	}

	public void toFile() {
		try {
			PrintWriter pw = new PrintWriter(new FileWriter(name+".nfo"));
			pw.write(this.toString());
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
